﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace CCF20
{
    public class DataContentControl : ContentControl
    {
        public readonly DependencyProperty EvalValueProperty = DependencyProperty.Register("EvalValue", typeof(object), typeof(DataContentControl), new PropertyMetadata(null, OnEvalValuePropertyChanged));

        private static void OnEvalValuePropertyChanged(DependencyObject changedObject, DependencyPropertyChangedEventArgs args)
        {
            var contentControl = (DataContentControl)changedObject;
            contentControl.OnContentChanged(args.OldValue, args.NewValue);
        }

        public readonly DependencyProperty ContentTemplateSelectorProperty = DependencyProperty.Register("ContentTemplateSelector", typeof(DataTemplateSelector), typeof(DataContentControl), new PropertyMetadata(null, OnContentTemplateSelectorPropertyChanged));
        private static void OnContentTemplateSelectorPropertyChanged(DependencyObject changedObject, DependencyPropertyChangedEventArgs args)
        {
            var contentControl = (DataContentControl)changedObject;
            contentControl.OnContentTemplateSelectorChanged((DataTemplateSelector)args.OldValue, (DataTemplateSelector)args.NewValue);
        }

        public DataContentControl()
        {
            //this.DefaultStyleKey = typeof(DataContentControl);
        }

        public object EvalValue
        {
            get { return GetValue(EvalValueProperty); }
            set { SetValue(EvalValueProperty, value); }
        }

        public DataTemplateSelector ContentTemplateSelector
        {
            get { return (DataTemplateSelector)GetValue(ContentTemplateSelectorProperty); }
            set { SetValue(ContentTemplateSelectorProperty, value); }
        }

        protected override void OnContentChanged(object oldValue, object newValue)
        {
            RefreshContentPresenter();
        }

        protected virtual void OnContentTemplateSelectorChanged(DataTemplateSelector oldValue, DataTemplateSelector newValue)
        {
            RefreshContentPresenter();
        }

        private void RefreshContentPresenter()
        {
            if (EvalValue == null)
                return;
            DataTemplate template = null;

            if (ContentTemplateSelector != null)
                template = ContentTemplateSelector.SelectTemplate(EvalValue, this);

            this.ContentTemplate = template;
        }
    }


    public class DataTemplateSelector
    {
        public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            return null;
        }
    }
}
